package net.wantongtech.xa.uploadbasicinfo.service;

import com.wtkj.exception.BusinessException;
import com.wtkj.vo.dzzf.base.kfzx.ClCardRefInfo;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.CancelCardRefundDao;
import net.wantongtech.xa.uploadbasicinfo.vo.RefundExcelModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 处理销卡退费数据服务实现
 *
 * @author MaShibo
 * 日期 :  2020/1/3
 */
@Slf4j
@Service
public class DealWithRefundDataService {

    @Resource
    private CancelCardRefundDao cancelCardRefundDao;

    private final TransactionTemplate transactionTemplate;

    @Autowired
    public DealWithRefundDataService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }


    public void dealWith() {
        List<RefundExcelModel> refundModelList = cancelCardRefundDao.queryRefundDataList();
        log.info("共有{}条待处理的销卡退款数据", refundModelList.size());
        if (refundModelList.isEmpty()) {
            return;
        }
        refundModelList.forEach(refundExcelModel -> {
            try {
                transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                        process(refundExcelModel);
                    }
                });
            } catch (Exception e) {
                String errorInfo = e.getMessage();
                log.error(errorInfo);
                try {
                    RefundExcelModel update = new RefundExcelModel();
                    update.setId(refundExcelModel.getId());
                    update.setErrorInfo(errorInfo);
                    update.setState(2);
                    cancelCardRefundDao.updateObject(update);
                } catch (Exception e1) {
                    log.error(e1.getMessage(), e1);
                }
            }
        });
    }

    private void process(RefundExcelModel model) {
        String vehPlate = model.getVehPlate();
        String cardNo = model.getCardNo();

        if (StringUtils.isBlank(vehPlate) || StringUtils.isBlank(cardNo)) {
            throw new BusinessException("车牌号或卡号为空");
        }

        if (StringUtils.length(cardNo) != 20) {
            throw new BusinessException(String.format("卡号%s，格式错误", cardNo));
        }

        log.info("开始处理数据：{}", model.toString());

        List<ClCardRefInfo> clCardRefInfoList = cancelCardRefundDao.queryRefundInfo(vehPlate, cardNo.substring(4));
        if (clCardRefInfoList.isEmpty()) {
            throw new BusinessException(String.format("车牌号为：%s，卡号为：%s的销卡退款记录不存在", vehPlate, cardNo));
        }
        if (clCardRefInfoList.size() > 1) {
            throw new BusinessException(String.format("车牌号：%s，卡号：%s，存在多条销卡退款记录", vehPlate, cardNo));
        }
        ClCardRefInfo clCardRefInfo = clCardRefInfoList.get(0);
        model.setPhoneNo(clCardRefInfo.getPhoneNo());
        cancelCardRefundDao.updateObject(model);

        Integer state = clCardRefInfo.getState();
        if (state == 2) {
            throw new BusinessException(String.format("车牌号：%s，卡号：%s，对应销卡退款记录已退款", vehPlate, cardNo));
        }
        if (state != 1) {
            throw new BusinessException(String.format("车牌号：%s，卡号：%s，对应销卡退款记录尚未确认", vehPlate, cardNo));
        }

        String bankAccountNo = clCardRefInfo.getBankAccountNo();
        String bankNo = model.getBankNo();
        if (!StringUtils.equals(bankAccountNo, bankNo)) {
            throw new BusinessException(String.format("申请退款银行账户号：%s，与确认退款银行账户号：%s，不一致", bankAccountNo, bankNo));
        }

        List<String> accountIdList = cancelCardRefundDao.queryAccountInfo(clCardRefInfo.getTradeNo());
        if (accountIdList.isEmpty()) {
            throw new BusinessException(String.format("车牌号：%s，卡号：%s对应账户信息不存在", vehPlate, cardNo));
        }
        if (accountIdList.size() > 1) {
            throw new BusinessException(String.format("车牌号：%s，卡号：%s存在多条账户信息", vehPlate, cardNo));
        }

        int count = cancelCardRefundDao.updateBankOrderData("20200615", clCardRefInfo.getTradeNo());

        log.info("更新销卡退款记录状态{}", count > 0 ? "成功" : "失败");

        String accountId = accountIdList.get(0);
        count = cancelCardRefundDao.updateAccount(accountId, model.getBackMny());
        log.info("更新账户余额{}", count > 0 ? "成功" : "失败");

        updateSuccess(model);
    }

    private void updateSuccess(RefundExcelModel model) {
        RefundExcelModel update = new RefundExcelModel();
        update.setId(model.getId());
        update.setState(1);
        cancelCardRefundDao.updateObject(update);
    }

}
